package com.yuliang.ai.websocket;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author Huangkai
 */
@Component
@Slf4j
@ServerEndpoint("/websocket/{deviceInfo}")
public class WebSocketServer {

    /**
     * 线程安全的无序的集合
     */
    private static final CopyOnWriteArraySet<Session> SESSIONS = new CopyOnWriteArraySet<>();

    /**
     * 存储在线连接数
     */
    private static final Map<String, Session> SESSION_POOL = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "deviceInfo") String deviceInfo) {
        try {
            //如果曾经连接过了，先删除以前的，
            if(SESSION_POOL.containsKey(deviceInfo)){
                Session getSession = SESSION_POOL.get(deviceInfo);
                SESSIONS.remove(getSession);
                SESSION_POOL.remove(deviceInfo);
            }
            log.info("连接的设备id{}", deviceInfo);
            SESSIONS.add(session);
            SESSION_POOL.put(deviceInfo, session);
            log.info("【WebSocket消息】有新的连接，总数为：" + SESSIONS.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session) {
        try {
            SESSIONS.remove(session);
            log.info("【WebSocket消息】连接断开，总数为：" + SESSIONS.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnMessage
    public void onMessage(String message) {
        log.info("【WebSocket消息】收到客户端消息：" + message);
    }
    /**
     * 此为单点消息
     *
     * @param deviceInfo  设备信息
     * @param resultJSON 消息
     */
    public void sendOneMessage(String deviceInfo, JSONObject resultJSON) {
        if(null != resultJSON){
            if(SESSION_POOL.containsKey(deviceInfo)){
                Session session = SESSION_POOL.get(deviceInfo);
                try{
                    log.info("返回的结果{}", resultJSON);
                    log.info("websocket是否打开{}", session.isOpen());
                    if (session.isOpen()) {
                        try {
                            synchronized (session) {
                                session.getAsyncRemote().sendText(resultJSON.toJSONString());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }else{
                        //如果没有连接，则删除该会话信息
                        SESSION_POOL.remove(deviceInfo);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

    public void sendAllMessage(String message) {
        log.info("【WebSocket消息】广播消息：" + message);
        for (Session session : SESSIONS) {
            try {
                if (session.isOpen()) {
                    session.getAsyncRemote().sendText(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
